#include <SDL.h>
#include <SDL_image.h>
#include <assert.h>
#include "scr_texture.h"
#include "scr_game.h"

SCRTexture::SCRTexture(const std::string& Filename, const SCRTextureAlpha::Enum& Alpha)
	: SCRResource()
	, m_pTexture(NULL)
{
	SDL_Surface* pOriginalImage = IMG_Load(Filename.c_str());
	if (pOriginalImage)
	{
		m_Filename = Filename;
		if (SCRTextureAlpha::HAS_ALPHA == Alpha)
		{
			m_pTexture = SDL_DisplayFormatAlpha(pOriginalImage);
		}
		else
		{
			m_pTexture = SDL_DisplayFormat(pOriginalImage);
		}
		SDL_FreeSurface(pOriginalImage);
		m_IsValid = true;
	}
}

SCRTexture::~SCRTexture()
{
	if (m_pTexture)
	{
		SDL_FreeSurface(m_pTexture);
	}
}

void SCRTexture::Draw(const SCRRect& Dest, const SCRRect& Source)
{
	assert(m_pTexture);

	SDL_Rect SourceRect = { (Sint16)Source.m_X, (Sint16)Source.m_Y, (Uint16)Source.m_Width, (Uint16)Source.m_Height };
	SDL_Rect DestRect = { (Sint16)Dest.m_X, (Sint16)Dest.m_Y, (Uint16)Dest.m_Width, (Uint16)Dest.m_Height };
	SDL_BlitSurface(m_pTexture, &SourceRect, SCRGame::GetInstance()->GetScreen(), &DestRect);
}

void SCRTexture::Draw(const int& X, const int& Y, const SCRRect& Source)
{
	assert(m_pTexture);

	SDL_Rect SourceRect = { (Sint16)Source.m_X, (Sint16)Source.m_Y, (Uint16)Source.m_Width, (Uint16)Source.m_Height };
	SDL_Rect DestRect = { (Sint16)X, (Sint16)Y, (Uint16)Source.m_Width, (Uint16)Source.m_Height };
	SDL_BlitSurface(m_pTexture, &SourceRect, SCRGame::GetInstance()->GetScreen(), &DestRect);
}

void SCRTexture::Draw(const int& X, const int& Y)
{
	assert(m_pTexture);

	SDL_Rect DestRect = { (Sint16)X, (Sint16)Y, 0, 0 };
	SDL_BlitSurface(m_pTexture, NULL, SCRGame::GetInstance()->GetScreen(), &DestRect);
}

void SCRTexture::Reload()
{
	if (m_pTexture)
	{
		SDL_FreeSurface(m_pTexture);
	}

	SDL_Surface* pOriginalImage = IMG_Load(m_Filename.c_str());
	if (pOriginalImage)
	{
		m_pTexture = SDL_DisplayFormat(pOriginalImage);
		SDL_FreeSurface(pOriginalImage);
		m_IsValid = true;
	}
}
